from typing import List

import random
import tempfile
import os
import logging
import shutil
import hashlib
import logging


def random_str(random_length=6):
    """
    生成随机字符串作为验证码
    :param random_length: 字符串长度,默认为6
    :return: 随机字符串
    """

    string = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    for i in range(random_length):
        string += chars[random.randint(0, length)]
    return string


def get_tempfile_path(suffix: str):
    """生成临时文件路径"""

    tempfolder = os.path.join(tempfile.gettempdir(), "nusic-server")
    if not os.path.exists(tempfolder):
        os.mkdir(tempfolder)
    return tempfile.mkstemp(suffix=suffix, dir=tempfolder)[1]


def clean_tempfile(max_size: int) -> int:
    """清理临时文件"""

    del_count = 0
    tempfolder = os.path.join(tempfile.gettempdir(), "nusic-server")
    if os.path.exists(tempfolder):

        # 存在时查询文件大小
        if os.path.getsize(tempfolder) > max_size:

            # 按修改时间对文件排序
            tpftimes = []
            for tpf in os.listdir(tempfolder):
                full_tpf = os.path.join(tempfolder, tpf)
                tpftimes.append((full_tpf, os.path.getmtime(full_tpf)))
            tpftimes.sort(key=lambda x: x[1])

            # 循环删除文件
            del_size = os.path.getsize(tempfolder) - max_size
            for tpf in tpftimes:
                if del_size > 0:
                    del_size = del_size - os.path.getsize(tpf[0])
                    os.remove(tpf[0])
                    logging.debug(f"file {tpf[0]} deleted")
                    del_count += 1

    return del_count


def clean_empty_folder(dir: str, ignore_dirs: List[str]) -> int:
    """清理空文件夹"""

    if not os.path.exists(dir):
        return 0
    del_count = 0
    files = os.listdir(dir)  # 获取路径下的子文件(夹)列表
    if files is None or files.__len__() == 0 or (files.__len__() == 1 and files[0] == ".DS_Store"):
        # 文件夹为空 或 里面只有Mac的隐藏文件
        if not ignore_dirs.__contains__(dir):
            shutil.rmtree(dir)
            del_count += 1

    for file in files:
        fullpath = os.path.join(dir, file)
        if os.path.isdir(fullpath):
            del_count += clean_empty_folder(fullpath, ignore_dirs)

    return del_count


def md5(text: str):
    md5obj = hashlib.md5()
    md5obj.update(text.encode("utf-8"))
    return md5obj.hexdigest()


def initLogger():
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    ch = logging.StreamHandler()
    fh = logging.FileHandler(filename="./nusic-server.log")
    formatter = logging.Formatter(
        "%(asctime)s %(module)s.%(funcName)s %(lineno)d: %(levelname)s - %(message)s")
    ch.setFormatter(formatter)
    fh.setFormatter(formatter)
    logger.addHandler(ch)
    logger.addHandler(fh)
